package com.project.dao.impl;

import com.project.bean.CityBean;
import com.project.bean.CountryBean;
import com.project.dao.ICityDao;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Repository
public class CityDaoImpl extends BaseDao implements ICityDao {
    @Override
    public List<CityBean> findByCountry(int countryId) {
        List<CityBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps=con.prepareStatement("select * from t_city where fk_cityId=?");
            ps.setObject(1,countryId);
            rs=ps.executeQuery();
            while (rs.next()){
                CityBean city =getCity(rs);
                list.add(city);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.close();
        }

        return list;
    }

    private CityBean getCity(ResultSet rs) throws SQLException {
        CityBean city = new CityBean();
        city.setId(rs.getInt("pk_cityId"));
        city.setName(rs.getString("city_name"));
        CountryBean country = new CountryBean();
        country.setId(rs.getInt("fk_cityId"));
        city.setCountry(country);
        return city;
    }
}
